/**
 * Created by EEO on 2017/6/13.
 */
//js格式化日期函数
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours() % 24 == 0 ? 24 : this.getHours() % 24,   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
};
require(['init'], function () {
    var initialLangCode = 'en';
    var $box;
    var id;
    var doctorId;
    var studentuid;
    // 生成日历 日历展示
    if (!localStorage.lang) {
        localStorage.setItem('lang', 'zh');
    }
    var dayNamesShort;
    var titleFormat;

    if (localStorage.lang && localStorage.lang == 'zh') {
        dayNamesShort = ["周日  ", "周一 ", "周二 ", "周三 ", "周四 ", "周五  ", "周六 "];
        titleFormat='yyyy年MM月';
    }
    else {
        dayNamesShort = ["Sunday  ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday  ", "Saturday "];
        titleFormat='yyyy Year MM';
    }
    var calendar = $('#calendar').fullCalendar({
        header: {
            left: 'prev,next',
            center: 'title',
            right: 'today',
        },
        titleFormat:titleFormat,
        defaultDate: '',
        lang: 'zh-cn',
        dayNamesShort: dayNamesShort,
        Mutilines: true,
        eventLimitText: 'more',
        buttonIcons: false, // show the prev/next text
        weekMode: 'liquid',
        //周视图prev Start
        viewRender: function (view) {
            var viewName = view.name;
            //开始日期
            var start = view.start;
            var startDay = start.format("yyyy-MM-dd");
            //结束日期
            var end = view.end;
            var endDay = end.format("yyyy-MM-dd");
            //清除之前渲染的数据
            if (localStorage.lang && localStorage.lang == 'en') {
                $(".fc-header-title h2").html($(".fc-header-title h2").text()+" Month")
                $('.fc-button-today').html('today')
            }
            $("#calendar").fullCalendar('removeEvents');
            $.ajax({
                url: ' /api/user/current',
                type: 'get',
                success: function (data) {
                    doctorId = data.data.userid;
                    $.ajax({
                        url: ' /api/student/user/' + doctorId,
                        type: 'get',
                        success: function (data) {
                            studentuid = data.data.studentuid;
                            $.ajax({
                                type: "get",
                                url: '/api/schedule/student/' + studentuid,
                                dataType: "json",
                                data: {
                                    begintime: startDay,
                                    endtime: endDay
                                },
                                success: function (data) {
                                    let dataNew = [];
                                    var eventServer = [];
                                    data.data.map((item) => {
                                        item['begintime'] = item['begintime'].split(' ')[0];
                                        let obj = {};
                                        obj['date'] = item['begintime'];
                                        obj['courseList'] = [];
                                        if (dataNew.some((it) => it['date'] == obj['date'])) {
                                            // 如果该时间点已经存在 将此对象 放入同时间段的dataList 数组中
                                            let findObj = dataNew.filter((ele) => ele['date'] == obj['date'])[0];
                                            findObj['courseList'].push(item)
                                        } else {
                                            // 如果该时间点不存在 创建此时间点 并将对象放入数组
                                            obj['courseList'].push(item);
                                            dataNew.push(obj)
                                        }
                                    });
                                    var $div = $('<div class="pos"></div>');
                                    $div.css('position', 'relative');
                                    $('.fc-day-number').wrap($div);
                                    $.each(dataNew, function (i, t) {
                                        var timer = t.date;
                                        var curCourseList = t.courseList;
                                        $.each(curCourseList, function (i, t) {
                                            //  这里拿到的 是每一节课的  scheduleid
                                        });
                                        var dateStr = t.date;
                                        var len = t.courseList.length;
                                        var $dayCover = $('[data-date="' + dateStr + '"]');
                                        var $span = $('<span class=" lessons">' + len + '' + i18next.t('timetable.lessons') + '</span>').appendTo($dayCover.find('.fc-day-number'));
                                        $box = $(' <div class="div"><p class="o"></p></div>');
                                        $('.fc-day-number').css('float', 'left');
                                        var time = curCourseList[0].period.split('-');
                                        var day = t.date + '' + time[1];
                                        var curTime = new Date();
                                        var endTime = Date.parse(day.replace(/-/g, "/"));  //当前课程时间
                                        var go = '<button class="button" data-id="' + curCourseList[0].scheduleid + '" style="border: none;background: #fff; color:' + checkColor() + ';position: absolute;top:-50px;right: 0 ;float: right;margin-right: 19px">' + checkName() + '</button>';

                                        function checkColor() {
                                            //判断颜色
                                            return curTime.getTime() > endTime ? "#999" : "#32ab9e";
                                        }

                                        function checkName() {
                                            //判断是否结束
                                            return curTime.getTime() > endTime ? i18next.t('timetable.over') : i18next.t('timetable.goclassroom');
                                        }

                                        var $Data = $('<div class="fc-day-Data" style="position: relative;z-index: 8"></div>').appendTo($dayCover);
                                        $Data.append(go);
                                        if (curCourseList.length == 1) {
                                            eventServer.push(curCourseList[0]);
                                        } else {
                                            eventServer.push(curCourseList[0]);
                                            //hover  最多只显示一条
                                            var str = '';
                                            str += '  <span class="three" style="float: right;"></span>';
                                            var $boxt = $('<div class="divto"></div>');
                                            $.each(curCourseList, function (i, t) {
                                                var timeT = t.period.split('-');
                                                var dayT = timer + '' + timeT[1];
                                                var curTimeT = new Date();
                                                var endTimeT = new Date(Date.parse(dayT.replace(/-/g, "/")));  //当前课程时间
                                                var a = '<button class="button btn" style="border: none;margin-left:-6px;background: #fff;color:' + checkColor() + '" data-id="' + t.scheduleid + '">' + checkName() + '</button>';

                                                function checkColor() {
                                                    //判断颜色
                                                    return curTimeT > endTimeT ? "#999" : "#32ab9e";
                                                }

                                                function checkName() {
                                                    return curTimeT > endTimeT ? i18next.t('timetable.over') : i18next.t('timetable.goclassroom');
                                                }

                                                str += '<div class="content">\
                                 <span class="fc-event-title"> ' + t.period + '<br>' + t.name + '</span>\
                                 <br><span>' + i18next.t('timetable.name') + ':' + t.teacherName + '</span>\
                                 <br><br>' + a + '\
                                 </div>';
                                            });
                                            $boxt.append(str);
                                            $box.append($boxt)
                                            $dayCover.find('.fc-day-number').find('.lessons').append($box);
                                        }
                                        eventServer.push({
                                            title: curCourseList[0].period + '\r\n' + curCourseList[0].name + '\r\n' + '' + i18next.t('timetable.name') + ':' + curCourseList[0].teacherName,  // 这里就是日志里显示的 内容 就这一个
                                            start: t.date,       //这里根据日期 插入指定日期
                                            end: t.endtime,
                                            backgroundColor: "#fff",
                                            textColor: "#24272d",
                                            className: 'title'
                                        });
                                    });
                                    var result = eventServer;
                                    $.each(result, function (index, term) {
                                        $("#calendar").fullCalendar('renderEvent', term, true);
                                    });
                                    $('button').on('click', function (e) {
                                        e = e || window.event;
                                        var tar = e.target || e.srcElement;
                                        if (tar.innerHTML === '进入教室' || tar.innerHTML === 'classroom') {
                                            var classID = $(e.target).data("id");
                                            $.ajax({
                                                url: '/api/schedule/' + classID + '/wakeup',
                                                type: 'get',
                                                data: {
                                                    type: '3',
                                                    userid: doctorId    //  doctorId
                                                },
                                                success: function (data) {   //data   进入教室的url
                                                    console.log(data);
                                                    parent.window.location.href = data.data;
                                                }
                                            });
                                        }
                                    });
                                    $box.on("click", ".button", function (e) {
                                        e = e || window.event;
                                        var tar = e.target || e.srcElement;
                                        if (tar.innerHTML === '进入教室' || tar.innerHTML === 'classroom') {
                                            var classID = $(e.target).data("id");
                                            $.ajax({
                                                url: '/api/schedule/' + classID + '/wakeup',
                                                type: 'get',
                                                data: {
                                                    type: '3',
                                                    userid: doctorId
                                                },
                                                success: function (data) {
                                                    console.log(data);
                                                    parent.window.location.href = data.data;
                                                }
                                            });
                                        }
                                    })
                                }
                            })
                        }
                    })
                }
            })

        },
    });


});




